package com.hschinese.pronunciation.utils;

import android.content.Context;

import com.hschinese.pronunciation.activity.MyApplication;
import com.hschinese.pronunciation.bean.AppDataBean;
import com.hschinese.pronunciation.bean.TestChinesePraciticeBean;
import com.hschinese.pronunciation.bean.TestResultBean;
import com.hschinese.pronunciation.db.DBHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import studychinese.model.TextRecultBean;
import studychinese.utils.SPUtils;

/**
 * Created by wo on 2015/10/29.
 * 解析所有的Txt数据，并将数据保存在数据库
 */
public class ParseTxtDataUtil {
    private Context context = null;
    private static ParseTxtDataUtil mInstance = null;

    private InputStreamReader inputReader = null;
    private BufferedReader bufReader = null;

    private List<AppDataBean> mAppdataList = null;
    private List<TestResultBean> mTestResultList = null;

    final String consonants = "consonants.txt";
    final String doublePhone = "doublePhone.txt";
    final String excise = "excise.txt";
    final String exciseFirst = "exciseFirst.txt";
    final String exciseSecond = "exciseSecond.txt";
    final String noticeMatters = "noticeMatters.txt";
    final String singlePhone = "singlePhone.txt";
    final String toneKnowledges = "toneKnowledges.txt";
    final String vowels = "vowels.txt";
    final String exciselistening = "exciselistening.txt";
    final String exciselisteningsingle = "exciselisteningsingle.txt";
    final String consruction = "consruction.txt";
    final String chinapracitice = "chinapracitice.txt";
    final String read = "read.txt";

    private ParseTxtDataUtil(Context cxt) {
        TextRecultBean testResultBean = new TextRecultBean();
        testResultBean.setState(0);
        List<TextRecultBean.DataBean> dataBeen = new ArrayList<>();
        testResultBean.setData(dataBeen);
        SPUtils.putObject(MyApplication.getInstance(), "testResultBean", "testResultBean",testResultBean);
        TestChinesePraciticeBean testChinesePraciticeBean = new TestChinesePraciticeBean();
        testChinesePraciticeBean.setState(0);
        List<TestChinesePraciticeBean.DataBean> testChinesePraciticeBeanList = new ArrayList<>();
        testChinesePraciticeBean.setData(testChinesePraciticeBeanList);
        SPUtils.putObject(MyApplication.getInstance(), "testChinesePraciticeBean", "testChinesePraciticeBean",testChinesePraciticeBean);
        context = cxt;
//        getFromAssetsTest();
        mAppdataList = new ArrayList<AppDataBean>();
        mTestResultList = new ArrayList<TestResultBean>();
        getFromAssets(consonants, true);
        getFromAssets(doublePhone, true);
        getFromAssets(excise, true);
        getFromAssets(exciseFirst, true);
        getFromAssets(exciseSecond, true);
        getFromAssets(noticeMatters, true);
        getFromAssets(singlePhone, true);
        getFromAssets(vowels, true);
        getFromAssets(exciselistening, true);
        getFromAssets(exciselisteningsingle, true);
        getFromAssets(consruction, true);
        getFromAssets(chinapracitice, true);
        getFromAssets(read, true);
        getFromAssets(toneKnowledges, false);

        // 写数据库
        // TODO 必须是第一次才进行数据库的创建和写数据到数据库，否则跳过
        Logger.e("xionghy-mAppData size: " + mAppdataList.size());
        Logger.e("xionghy-mTestResultList size: " + mTestResultList.size());
        DBHelper.getInstance(cxt).insertAppData(mAppdataList);
        DBHelper.getInstance(cxt).insetTestResult(mTestResultList);
    }

    public static ParseTxtDataUtil getInstance (Context cxt) {
        synchronized (ParseTxtDataUtil.class) {
            if (mInstance == null) {
                mInstance = new ParseTxtDataUtil(cxt);
            }
            return mInstance;
        }
    }

    public void getFromAssetsTest() {
        try {
            inputReader = new InputStreamReader(context.getResources().getAssets().open("a/a.txt") );
            bufReader = new BufferedReader(inputReader);
            String line="";
            while ((line = bufReader.readLine()) != null) {
                Logger.e("ParseTxtDataUtil: " + line);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputReader.close();
                bufReader.close();
                inputReader = null;
                bufReader = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param fileName 要解析的文件名
     * @param type 要解析的文件类型（AppDataBean<true>还是TestResultBean<false>）
     */
    public void getFromAssets(String fileName, boolean type){
        try {
            inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName) );
            bufReader = new BufferedReader(inputReader);
            String line="";
            boolean b = true;
            while((line = bufReader.readLine()) != null) {
                if (b) {
                    b = false;
                    continue;
                }
                if (line == null || line.isEmpty()) continue;
                if (type) {
                    if (line.split(",").length != 9) {
                        continue;
                    }
                    saveAppData(line);
                } else {
                    if (line.split(",").length != 6) {
                        continue;
                    }
                    Logger.e("xionghy - line: " + line);
                    saveTestResult(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputReader.close();
                bufReader.close();
                inputReader = null;
                bufReader = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void saveAppData(String line) {
        AppDataBean da = new AppDataBean();
        String vals[] = line.split(",");
        if (vals[0] != null && !vals[0].isEmpty()) {
            da.setChinese(vals[0]);
        }
        if (vals[1] != null && !vals[1].isEmpty()) {
            da.setPinyin(vals[1]);
        }
        if (vals[2] != null && !vals[2].isEmpty()) {
            da.setPhone(vals[2]);
        }
        if (vals[3] != null && !vals[3].isEmpty()) {
            da.setTone(vals[3]);
        }
        if (vals[4] != null && !vals[4].isEmpty()) {
            da.setAudioName(vals[4]);
        }
        if (vals[5] != null && !vals[5].isEmpty()) {
            da.setPicName(vals[5]);
        }
        if (vals[6] != null && !vals[6].isEmpty()) {
            da.setType(Integer.valueOf(vals[6]));
        }
        if (vals[7] != null && !vals[7].isEmpty()) {
            da.setGroupID(Integer.valueOf(vals[7]));
        }
        if (vals[8] != null && !vals[8].isEmpty()) {
            da.setWeight(Integer.valueOf(vals[8]));
        }
        mAppdataList.add(da);
    }

    private void saveTestResult(String line) {
        TestResultBean da = new TestResultBean();
        String vals[] = line.split(",");
        if (vals[0] != null && !vals[0].isEmpty()) {
            da.setTone(vals[0]);
        }
        if (vals[1] != null && !vals[1].isEmpty()) {
            da.setRightTimes(Integer.valueOf(vals[1]));
        }
        if (vals[2] != null && !vals[2].isEmpty()) {
            da.setWrongTimes(Integer.valueOf(vals[2]));
        }
        if (vals[3] != null && !vals[3].isEmpty()) {
            da.setWrongTones(Integer.valueOf(vals[3]));
        }
        if (vals[4] != null && !vals[4].isEmpty()) {
            da.setType(Integer.valueOf(vals[4]));
        }
        if (vals[5] != null && !vals[5].isEmpty()) {
            da.setWeight(Integer.valueOf(vals[5]));
        }
        mTestResultList.add(da);
    }
}
